package com.kool.kauth.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author luyu
 */
@Slf4j
public class LogThread extends Thread {
    private InputStream inputStream;
    private String filepath;

    public LogThread(InputStream inputStream, String filepath) {
        this.inputStream = inputStream;
        this.filepath = filepath;
    }

    @Override
    public void run() {
        log.debug("input thread started.");
        try {
            int read = 0;
            byte[] buff = new byte[1024 * 8];
            FileOutputStream fileOutputStream = new FileOutputStream(this.filepath, true);
            while ((read = this.inputStream.read(buff)) != -1) {
                fileOutputStream.write(buff, 0, read);
//                System.out.println(new String(buff));
            }

            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            close(this.inputStream);
        }
    }

    private void close(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            inputStream = null;
        }

    }
}
